// lib/services/share_service.dart
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';

/// 分享内容模型
class ShareContent {
  final String title;
  final String content;
  final String url;
  final String? imageUrl;

  const ShareContent({
    required this.title,
    required this.content,
    required this.url,
    this.imageUrl,
  });
}

/// 分享服务类 - 单例模式
class ShareService {
  // 私有构造函数
  ShareService._internal();

  // 单例实例
  static final ShareService _instance = ShareService._internal();

  // 获取单例实例的工厂构造函数
  factory ShareService() => _instance;

  // 静态方法获取实例
  static ShareService get instance => _instance;

  // Fluwx实例
  final Fluwx fluwx = Fluwx();

  // 微信SDK注册状态
  static bool _isWeChatRegistered = false;

  // 获取微信SDK注册状态
  bool get isWeChatRegistered => _isWeChatRegistered;

  /// 初始化微信SDK
  Future<void> initWeChat(String appId, {String? universalLink}) async {
    try {
      bool result = await fluwx.registerApi(
        appId: appId,
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: universalLink,
      );

      _isWeChatRegistered = result;
      debugPrint('微信SDK初始化${result ? "成功" : "失败"}');
    } catch (e) {
      debugPrint('微信SDK初始化异常: $e');
      _isWeChatRegistered = false;
    }
  }

  /// 显示分享弹框
  void showShareDialog(BuildContext context, ShareContent shareContent) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) =>
          _ShareBottomSheet(shareContent: shareContent),
    );
  }

  /// 检查微信是否可用
  Future<bool> isWeChatAvailable() async {
    if (!_isWeChatRegistered) {
      return false;
    }

    try {
      bool isInstalled = await fluwx.isWeChatInstalled;
      return isInstalled;
    } catch (e) {
      debugPrint('检查微信状态异常: $e');
      return false;
    }
  }

  /// 直接分享到微信好友
  Future<void> shareToWeChatSession(ShareContent content) async {
    await _shareToWeChat(content, WeChatScene.session);
  }

  /// 直接分享到微信朋友圈
  Future<void> shareToWeChatTimeline(ShareContent content) async {
    await _shareToWeChat(content, WeChatScene.timeline);
  }

  /// 直接分享到微信收藏
  Future<void> shareToWeChatFavorite(ShareContent content) async {
    await _shareToWeChat(content, WeChatScene.favorite);
  }

  /// 分享纯文本到微信
  Future<void> shareTextToWeChat(
    String text, {
    WeChatScene scene = WeChatScene.session,
  }) async {
    await _shareTextToWeChat(text, scene);
  }

  /// 内部方法：分享到微信
  Future<void> _shareToWeChat(ShareContent content, WeChatScene scene) async {
    if (!_isWeChatRegistered) {
      debugPrint('微信SDK未初始化');
      return;
    }

    try {
      WeChatShareWebPageModel shareModel = WeChatShareWebPageModel(
        content.url,
        title: content.title,
        description: content.content,
        scene: scene,
      );

      await fluwx.share(shareModel);
      debugPrint('分享请求已发送');
    } catch (e) {
      debugPrint('分享异常: $e');
    }
  }

  /// 内部方法：分享文本到微信
  Future<void> _shareTextToWeChat(String text, WeChatScene scene) async {
    if (!_isWeChatRegistered) {
      debugPrint('微信SDK未初始化');
      return;
    }

    try {
      WeChatShareTextModel shareModel = WeChatShareTextModel(
        text,
        scene: scene,
      );

      await fluwx.share(shareModel);
      debugPrint('文本分享请求已发送');
    } catch (e) {
      debugPrint('文本分享异常: $e');
    }
  }
}

/// 分享底部弹框组件
class _ShareBottomSheet extends StatelessWidget {
  final ShareContent shareContent;

  const _ShareBottomSheet({required this.shareContent});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 标题栏
            Container(
              padding: const EdgeInsets.all(16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '分享到',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  GestureDetector(
                    onTap: () => Navigator.of(context).pop(),
                    child: const Icon(Icons.close, color: Colors.grey),
                  ),
                ],
              ),
            ),

            const Divider(height: 1),

            // 分享选项网格
            Padding(
              padding: const EdgeInsets.all(20),
              child: GridView.count(
                shrinkWrap: true,
                crossAxisCount: 3,
                mainAxisSpacing: 20,
                crossAxisSpacing: 20,
                children: [
                  _buildShareItem(
                    context,
                    '微信',
                    Icons.wechat_outlined,
                    Colors.green,
                    () => _handleShare(context, 'wechat'),
                  ),
                  _buildShareItem(
                    context,
                    '朋友圈',
                    Icons.circle_outlined,
                    Colors.green,
                    () => _handleShare(context, 'timeline'),
                  ),
                  _buildShareItem(
                    context,
                    '收藏',
                    Icons.star_border,
                    Colors.orange,
                    () => _handleShare(context, 'favorite'),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  /// 构建分享选项
  Widget _buildShareItem(
    BuildContext context,
    String name,
    IconData icon,
    Color color,
    VoidCallback onTap,
  ) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(25),
            ),
            child: Icon(icon, color: color, size: 28),
          ),
          const SizedBox(height: 8),
          Text(
            name,
            style: const TextStyle(fontSize: 12, color: Colors.black87),
          ),
        ],
      ),
    );
  }

  /// 处理分享操作
  void _handleShare(BuildContext context, String platform) async {
    Navigator.of(context).pop(); // 关闭弹框

    final shareService = ShareService.instance;

    // 检查微信是否可用
    bool isAvailable = await shareService.isWeChatAvailable();
    if (!isAvailable) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('微信未安装或未初始化'),
            duration: Duration(seconds: 2),
          ),
        );
      }
      return;
    }

    switch (platform) {
      case 'wechat':
        shareService._shareToWeChat(shareContent, WeChatScene.session);
        break;
      case 'timeline':
        shareService._shareToWeChat(shareContent, WeChatScene.timeline);
        break;
      case 'favorite':
        shareService._shareToWeChat(shareContent, WeChatScene.favorite);
        break;
    }
  }
}
